package com.attendcollatesys.excel.linstener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.attendcollatesys.entity.ATDayDetails;
import com.attendcollatesys.entity.excel.ExcelATDayDetails;
import com.attendcollatesys.ex.handler.ex.ExcelContentCheckException;
import com.attendcollatesys.service.ATDayDetailsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

/**
 * 读取每日考勤明细sheet页的监听器  关于读取到的数据全部在这里进行处理
 * add by gzl
 * 2024年1月26日
 */

public class ExcelATDayDetailListener extends AnalysisEventListener<ExcelATDayDetails> {



    /**
     * 每隔100条存储数据库
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<ExcelATDayDetails> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ATDayDetailsService atDayDetailsService;

    private StringBuilder sheetHeadValue=new StringBuilder();

    private int count;


    private boolean checkFlag = false;


    public ExcelATDayDetailListener(ATDayDetailsService atDayDetailsService){
        this.atDayDetailsService=atDayDetailsService;
    }

    /**
     *  每读取一行执行此方法
     */
    @Override
    public void invoke(ExcelATDayDetails excelATDayDetails, AnalysisContext analysisContext) {
        //读取完表头就开始读取实际要录入的内容  此时需要校验的表头数据已全部拼装为一个字符串 这里再次压缩与先前压缩好的表头内容比对
        //项目为uft-8编码 选取其他编码格式 也会校验失败
//        if (!checkFlag) {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) {
//                gzipOut.write(sheetHeadValue.toString().getBytes());
//            } catch (Exception e) {
//                throw new R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TFwB4RMF8j7RW0gEhf/j2LMubX6zYNqmuYWm8f2f2dr5aIzclDNtKpB41hVHN+hIBMvSHlbG4jE9ZHSN1j5DF1IOzi1nxWyMqV5k5NkAKQSApqhaPobXVvSDCVJBErVG9mZJ5M7jQNkpWTjtKp841iUckG1AUIzn+rvNOOwbRx3klT6F1SuYlPUlz6Q5TctgZIkBayUFPYKhxH0ayP4rBbpwoY2HNlpXykvNOM0XaP7zs+G+s2L+LJ5SRuiJElgpSRx7K4Ome3AZPYLzX8/ws2m96uzzkao0X7ZGpAjVYkaNulRmXZIepg2mP3RddXl7DInLyV3gOuK6+ynp+kjGvsLsQETHZk5AAA=";
//            if(!Base64.getEncoder().encodeToString(baos.toByteArray()).equals(sheetHeadCode)){
//                System.out.println(Base64.getEncoder().encodeToString(baos.toByteArray()));
//               // throw new ExcelContentCheckException("每日考勤明细表头数据与预期不符");
//            }
//            checkFlag=!checkFlag;
//        }


        //过多空行时使用
//       analysisContext.readWorkbookHolder().setIgnoreEmptyRow(false);
        
        cachedDataList.add(excelATDayDetails);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }
    /**
     * 此方法会读取前表头内容
     */
//    @Override
//    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
//        ObjectMapper objectMapper = new ObjectMapper();
//        count++;
//        if(count==2)return;//导出人不用检验内容
//        try {
//            sheetHeadValue.append(objectMapper.writeValueAsString(headMap));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("文件头解析失败");
//        }
//
//    }

    /**
     * 在读取文件的最后执行
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(cachedDataList.size()>0){
            saveData();
        }
        System.out.println("每日考勤明细导入完毕");
    }



    private void saveData()  {
        ArrayList<ATDayDetails> atDayDetailList = new ArrayList<>();
        ArrayList<String> dayRtxList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (ExcelATDayDetails excelATDayDetails : cachedDataList) {

            dayRtxList.add(sdf.format(excelATDayDetails.getAttendanceDate()) + excelATDayDetails.getRtxAccount());

            ATDayDetails atDayDetails = new ATDayDetails();
            atDayDetails.setAttendanceDate(excelATDayDetails.getAttendanceMonth())
                    .setDateType(excelATDayDetails.getDateType())
                    .setAttendanceDay(excelATDayDetails.getAttendanceDate())
                    .setSectionMID(excelATDayDetails.getDepartmentManagerId())
                    .setName(excelATDayDetails.getName())
                    .setRtxNumber(excelATDayDetails.getRtxAccount())
                    .setCardInformation(excelATDayDetails.getReissueCardInfo())
                    .setCheckInTime(excelATDayDetails.getCheckInTime())
                    .setSignOutDate(excelATDayDetails.getCheckOutDate())
                    .setSignOutTime(excelATDayDetails.getCheckOutTime())
                    .setLeaveApplication(excelATDayDetails.getLeaveApplication())
                    .setLeaveType(excelATDayDetails.getLeaveType())
                    .setLeaveReason(excelATDayDetails.getLeaveReason())
                    .setOvertimeApplication(excelATDayDetails.getOvertimeApplication())
                    .setOvertimeContent(excelATDayDetails.getOvertimeContent())
                    .setEffectiveStateTime(excelATDayDetails.getValidOvertimeStartTime())
                    .setEffectiveEndTime(excelATDayDetails.getValidOvertimeEndTime())
                    .setExpectedWorkHours(excelATDayDetails.getScheduledWorkHours())
                    .setAbsenceWorkHours(excelATDayDetails.getAbsenteeismDeductionHours())
                    .setAbsentWorkHours(excelATDayDetails.getAdditionalAbsenceDeductionHours())
                    .setLateTimes(excelATDayDetails.getLateEarlyTimes())
                    .setLateWorkHours(excelATDayDetails.getLateEarlyDeductionHours())
                    .setOvertimeWorkHours(excelATDayDetails.getCalculatedOvertimeHours())
                    .setAttendanceHours(excelATDayDetails.getCalculatedAttendanceHours());
            atDayDetailList.add(atDayDetails);

        }
        //先根据签到日期和Rtx账号进行一次删除 避免重复导入
        atDayDetailsService.deleteByDayRtxList(dayRtxList);
        atDayDetailsService.insertAll(atDayDetailList);





    }


//过多空行时使用
//    @Override
//    public boolean hasNext(AnalysisContext context) {
//        if(RowTypeEnum.EMPTY.equals(context.readRowHolder().getRowType())){
//            doAfterAllAnalysed(context);
//            return false;
//        }
//        return super.hasNext(context);
//    }
}
